package cn.edu.seu.herald.informationplatform.dao.cookie;

import java.sql.SQLException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

abstract class SessionCookieAccess {
	
	private String _sessionId;
	
	SessionCookieAccess(HttpServletRequest request)
			throws SessionIdNotFound {
		Cookie cookie = getSessionIdCookie(request);
		_sessionId = cookie.getValue();
	}
	
	private Cookie getSessionIdCookie(
			HttpServletRequest request) throws SessionIdNotFound {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie: cookies) {
				String name = cookie.getName();
				if (name.equalsIgnoreCase(getSessionIdName())) {
					return cookie;
				}
			}
		}
		request.setAttribute("test", getSessionIdName());
		throw new SessionIdNotFound();
	}
	
	public final String getSessionId() {
		return _sessionId;
	}
	
	public abstract boolean isAuthorized() throws SQLException;
	
	public abstract String getUsername() throws SQLException;
	
	protected abstract String getSessionIdName();

}
